import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

// token过期检查
export const checkToken = () => {
  const token = localStorage.getItem('token')
  const expires = localStorage.getItem('tokenExpires')
  
  if (!token || !expires || Date.now() > parseInt(expires)) {
    localStorage.removeItem('token')
    localStorage.removeItem('tokenExpires')
    router.push('/login')
    return false
  }
  return token
}

// 创建请求实例
const request = axios.create({
  baseURL: 'https://fbox360.com/api'
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = checkToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(error.response?.data?.message || '请求失败')
    return Promise.reject(error)
  }
)

export default request 